<?php

class LoginAction extends BaseAction{	
    protected $SALT = 'LM';
    
    public function _empty() {
        $tpl = "../Include/App/Group/Bridge/Tpl/Public_404.html";
        $this->display($tpl);
    }
    
    //登录
    public function index($param=NULL){
        session('surl', $_SERVER['HTTP_REFERER']);
        if ($param['signuped']==1) {
            $this->assign('signuped', 1);
        }
    	$this->display();
    }
    
    function signup_checkEmailAjax() {
        $email = I('email');
        $where['email'] = array('eq', $email);
        $userRes = M('user')->where($where)->find();
        if($userRes){
            echo json_encode(FALSE);
        }
        else{
            echo json_encode(TRUE);//echo "";//"该邮箱地址可以使用";
        }
    }
    
    //昵称唯一性校验
    function signup_checkNicknameAjax() {
        $copname = I('companyname');
        $nickname = I('nickname');
        if (!empty($copname)) {
            $name = $copname;
        }
        if (!empty($nickname)) {
            $name = $nickname;
        }
        $where['nickname'] = array('eq', $name);
        $userRes = M('user_info')->where($where)->find();
        if($userRes) {
            $uid = $this->uid;
            if ($uid>0) {
                if ($userRes['uid']==$uid) {
                    echo json_encode(TRUE);
                    exit;
                }
            }
            echo json_encode(FALSE);
        }
        else{
            echo json_encode(TRUE);
            exit;
        }
    }
    
    //注册流程第二步
    function signup_step2() {
        
        import('ORG.Util.Verify');
        if(Verify::isEmpty(I('email'))==false
           || Verify::isEmpty(I('password'))==false
           || Verify::isEmpty(I('usertype'))==false){
            $this->redirect('Login/reg@'.getDomain());
            exit;
        }
        $utype = I('usertype');
        $email = I('email');
        $pwd = md5(I('password'));
        $where['email'] =  array('eq',$email);
        $userRes = M('user')->where($where)->find();
        if(!$userRes){
            $data = array(
                'email'    =>  $email,
                'pwd'      =>  $pwd,
                'ctime'    =>  time(),
            );
            $res = M('user')->add($data);
            if($res){
                //创建用户数据表
                $data = array(
                    'uid' => $res,
                    'utype' => $utype,
                    'nickname' => $email,
                    'teamname' => '',
                    'teamid' => -1,
                    'projectname' => '',
                    'projectid' => -1,
                    'uptime'=>  time(),
                );
                $resUserinfo = M('user_info')->add($data);
                
                //添加account表记录
                $account = array('uid'=>$res);
                M('account')->add($account);
                
                cookie('uid',$res,'expire=0&domain='.getDomain());
                $identifer = md5(G_SALT . md5($email . G_SALT));
                $token = md5(uniqid(rand(), TRUE));
                cookie('auth', "$email:$identifer:$token", "expire=0&domain=". getDomain());
                M('user')->where('id='.$res)->save(array('identifer'=>'logined'));//设置已登陆状态
                $this->assign("uid", $res);
                $this->assign('userinfo', $data);
            }
        }
        else {
            $this->redirect('Login/index@'.getDomain(), array("signuped"=>1));
        }
        $this->assign("on", 1);
        $tpl = '';
        
        $this->assign('rc', time());
        $this->assign('sn', session_name());
        $this->assign('sid', session_id());
        if($utype==1){
            $tpl = 'signup_person';
        }
        elseif ($utype==2) {
            $tpl = 'signup_company';
        }
        $this->display($tpl);
    }
    
    //发送账户激活邮件ajax
    public function activeaccount_ajax() {
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('name'))==false) {
            echo json_encode(array('success'=>0, 'msg'=>'参数错误!'));
            exit;
        }
        $name = I('name');
        $uid = $this->uid;
        if (empty($uid)) {
            echo json_encode(array('success'=>0, 'msg'=>'未登陆，无法发送激活邮件'));
            exit;
        }
        
        $ret = $this->recEmailVerify($name, $uid, true);
        if (!$ret) {
            echo json_encode(array('success'=>0,'msg'=>'发送失败，您可重新尝试'));
            exit;
        }
        else {
            echo json_encode(array('success'=>1,'msg'=>'成功发送，快去邮箱查收邮件，激活账户吧！'));
            exit;
        }
    }
    
    //$now 是否立即发送
    public function recEmailVerify($name, $uid, $now=false) {
        $ret = false;
        $now = time();
        $user = M('user')->where('id='.$uid)->find();
        //先删除旧token
        M('emailverify')->where('uid='.$uid)->delete();
        
        $token = md5($user['email'].$now);
        $verifyData = array(
            'token' => $token,
            'uid' => $uid,
            'ctime' => $now,
        );
        $ret = M('emailverify')->add($verifyData);
        $url = U('/Login/emailverify@'.getDomain(), 'code=1&token='.$token);//"http://".$_SERVER['HTTP_HOST']."/Login/emailverify/code/1/token/$token";
        $to = $user['email'];
        $subject = "欢迎您加入般若虾——中高端脑力兼职";
        $body = "亲爱的$name:<br/>&nbsp;&nbsp;&nbsp;&nbsp;感谢您注册般若虾，般若虾专注中高端脑力兼职，是中高端人才的聚集地，中小、初创企业的项目园。<br/>&nbsp;&nbsp;&nbsp;&nbsp;请点击如下链接完成邮箱验证，激活账户:<br/>&nbsp;&nbsp;&nbsp;&nbsp;<a href='".$url."'>$url</a><br/>";
        $body = mailPostfix($body);
        if ($now) {
            $ret = think_send_mail($to, $name, $subject, $body);
        }
        else {
            $ret = mailqueue_push($to, $name, $subject, $body);
        }
        return $ret;
    }
    
    //个人用户提交注册
    function signup_commitPersonAjax() {
        import('ORG.Util.Verify');
        if(Verify::isEmpty(I('nickname')) ==false
           || Verify::isEmpty(I('gender')) ==false
           || Verify::isEmpty(I('province')) ==false
           || Verify::isEmpty(I('city')) ==false
           || Verify::isEmpty(I('mobile')) ==false
           || Verify::isEmpty(I('birthdayYear')) ==false
           || Verify::isEmpty(I('birthdayMonth')) ==false
           || Verify::isEmpty(I('birthdayDay')) ==false
           || Verify::isEmpty(I('vocation')) ==false
           || Verify::isEmpty(I('workYears')) ==false
           || Verify::isEmpty(I('introduction'))==false
           ){
               ajaxf('参数错误');
        }
        
        $data = array();
        $data['utype'] = 1;
        if (Verify::isEmpty(I('uploadurl'))==true) {
            $url = I('uploadurl');
            if (substr($url, 0, 1)==='/') {
                $url = substr($url, 1);
            }
            $data['photo'] = $url;
        }
        
        $data['nickname'] = I('nickname');
        $data['gender'] = I('gender');
        $data['address'] = I('province') . ',' . I('city');
        $data['mobile'] = I('mobile');
        $data['birthday'] = I('birthdayYear') . '-' . I('birthdayMonth') . '-' . I('birthdayDay');
        $data['job'] = I('vocation');
        $data['exp'] = I('workYears');
        $data['about'] = I('introduction');
        
        
        $uid = $this->uid;
        $res = M('user_info')->where('uid='.$uid)->save($data);
        if(!$res){
            echo json_encode(array('success'=>0,'msg'=>'注册失败!'));
            exit;
        }
        echo json_encode(array('success'=>1));
    }
    
    //企业用户提交注册ajax
    public function signup_commitCompanyAjax() {
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('uploadurl'))==false
           || Verify::isEmpty(I('companyname'))==false
           || Verify::isEmpty(I('province'))==false
           || Verify::isEmpty(I('city'))==false
           || Verify::isEmpty(I('mobile'))==false
           || Verify::isEmpty(I('telephone'))==false
           || Verify::isEmpty(I('industry'))==false
           || Verify::isEmpty(I('shortname'))==false
           || Verify::isEmpty(I('contactname'))==false
           || Verify::isEmpty(I('contactemail'))==false) {
            echo json_encode(array('status'=>'error'));
            exit;
        }
        
        $data = array();
        $data['utype'] = 2;
        if (Verify::isEmpty(I('uploadurl'))==true) {
            $url = I('uploadurl');
            if (substr($url, 0, 1)==='/') {
                $url = substr($url, 1);
            }
            $data['photo'] = $url;
        }
    
        $data['nickname'] = I('companyname');//用"昵称"字段存储企业全称
        $data['address'] = I('province') . ',' . I('city');
        $data['contactname'] = I('contactname');
        $data['contactemail'] = I('contactemail');
        $data['mobile'] = I('mobile');
        $data['telephone'] = I('telephone');
        $data['industry'] = I('industry');
        $data['shortname'] = I('shortname');
        $data['teamid'] = -1;
        if (Verify::isEmpty(I('website'))) {
            $data['website'] = I('website');
        }
        if (Verify::isEmpty(I('intro'))) {
            $data['intro'] = I('intro');
        }
        if (Verify::isEmpty(I('culture'))) {
            $data['culture'] = I('culture');
        }
        
        $uid = $this->uid;
        $res = M('user_info')->where('uid='.$uid)->save($data);
        if(!$res){
            echo json_encode(array('success'=>0, 'msg'=>'注册失败!'));
            exit;
        }
        echo json_encode(array('success'=>1));
    }
	
    //提交登录
    public function login_ajax(){
        import('ORG.Util.Verify');
        $redirect = false;
        if(Verify::isEmpty(I('redirect'))==true){
            $redirect = true;
        }
    	$email = I('email');
        $remember = I('rem');
        Log::write('rem:'.$remember, Log::ERR);
    	$userpwd  = md5(I('userpwd'));
	$where['email'] = array('eq',$email);
	$arr = M('user')->where($where)->find();
        if($arr){
            if($userpwd == $arr['pwd']){
                cookie('uid', $arr['id'],'expire=0&domain='.getDomain());
                $ld = array('identifer'=>'logined', 'lastime'=>time(), 'lastip'=>get_client_ip());
                M('user')->where('id='.$arr['id'])->save($ld);//设置已登陆状态
                $userinfoTab = M('user_info')->where('uid='.$arr['id'])->find();
                if($userinfoTab){
                    if($remember){
                        $identifier = md5(G_SALT . md5($email . G_SALT));
                        $token = md5(uniqid(rand(), TRUE));
                        $timeout = 60 * 60 * 24 * 7;
                        $dl = time() + $timeout;
                        //存储会话信息
                        $sd = array();
                        $sd['token'] = $token;
                        $sd['timeout'] = $dl;
                        M('user')->where('id='.$arr['id'])->save($sd);
                        cookie('auth', "$email:$identifier:$token", "expire=$timeout&domain=".getDomain());
                    }
                    $retdata = array('success'=>1, 'nickname'=>$userinfoTab['nickname'], 'msg'=>'');
                    if($redirect){//登陆后跳转
                        $retdata['url'] = U('/@'.getDomain());
                        if(Verify::isEmpty(session('surl'))==true){
                            $surl = session('surl');
                            $retdata['url'] = $surl;
                            if(strstr($surl, 'reg')
                               || strstr($surl, 'resetpwd')
                               || !strstr($surl, $_SERVER['HTTP_HOST'])){//从注册页面过来的则不返回
                                $retdata['url'] = U('/@'.getDomain());
                            }
                        }
                    }
                    echo I('callback', 'callback').'('.  json_encode($retdata).')';
                    exit;
                }
                else{//若查询用户数据出错，则认为是恶意行为或数据无法恢复，不返回任何数据
                    exit;
                }
            }
            else{
                $this->jsonpf('密码输入错误，请重新填写');
            }
        }
        else{
            $this->jsonpf('用户不存在，请重新填写');
        }
    }
	
    //退出登录
    public function logout(){
        session_destroy();
        M('user')->where('id='.$this->uid)->setField('identifer', 'logout');
        $sn = session_name();
        cookie($sn, NULL);
        cookie('uid', NULL);
        cookie('auth', NULL);
    	$this->redirect('/@'.getDomain());    	 
    }
	
    //注册
    public function reg(){
    	$this->display();
    } 

    //验证码
    Public function verify(){
        ob_clean();
        import('ORG.Util.Image');
        Image::buildImageVerify($length=4, $mode=1, $type='png', $width=88, $height=32, $verifyName='verify');
        //调用buildImageVerify方法生成验证码，默认参数为（$length=4, $mode=1, $type='png', $width=48, $height=22, $verifyName='verify'），
    }
	
	//检验验证码是否正确
    public function verify_check() {
    	if (md5(I('verify')) == session('verify')) {
    		echo 1;
    	}
    	else {
    		echo 0;
    	}
    	exit;
    }
    
    //重置密码
    public function resetpwd() {
        $step = I('step',1);
        if($step==1){
            $this->display('resetpwd1');
        }
        elseif($step==2){
            $email = I('email');
            if(!$email){
                exit;
            }
            $resUserinfo = M('user')->table(array('xia_user'=>'user','xia_user_info'=>'userinfo'))->field('user.*, userinfo.protectemail')->where("email='".$email."' and user.id=userinfo.uid")->find();
            if($resUserinfo){
                //密保邮箱
                $pemail = hidemail($resUserinfo['protectemail']);
                if (strlen($pemail)>0) {
                    $this->assign('pemailFlag', 1);
                    $this->assign('pemail', $pemail);
                }
                else{
                    $this->assign('pemailFlag', 0);
                }
                
                //密保问题
                $protectQuestion = M('pwdprotect')->table(array('xia_pwdprotect'=>'pwdprotect','xia_dic'=>'dic'))->field('pwdprotect.*, dic.name')->where('pwdprotect.uid='.$resUserinfo['id'].' and pwdprotect.qid=dic.id')->select();
                if ($protectQuestion) {
                    $this->assign('qlist', $protectQuestion);
                }
                $this->assign('user', $resUserinfo);
            }
            $this->display('resetpwd2');
        }
    }
    
    //验证密保问题
    public function verifyQuest_ajax() {
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('uid'))==false
            || Verify::isEmpty(I('q1'))==false
            || Verify::isEmpty(I('a1'))==false
            || Verify::isEmpty(I('q2'))==false
            || Verify::isEmpty(I('a2'))==false
           ) {
               echo json_encode(array('success'=>0,'msg'=>'数据出错'));
               exit;
        }
        $uid = I('uid');
        $q1 = I('q1');
        $a1 = I('a1');
        $q2 = I('q2');
        $a2 = I('a2');
        
        $valid = 0;
        $resQp1 = M('pwdprotect')->where('uid='.$uid.' and qid='.$q1)->find();
        if($resQp1){
            if ($resQp1['answer']==$a1) {
                $valid = $valid + 1;
            }
        }
        $resQp2 = M('pwdprotect')->where('uid='.$uid.' and qid='.$q2)->find();
        if ($resQp2) {
            if ($resQp2['answer']==$a2) {
                $valid = $valid + 1;
            }
        }
        if ($valid==2) {
            //设置session
            session('uid', $uid);
            echo json_encode(array('success'=>1));
            exit;
        }
        else{
            echo json_encode(array('success'=>0,'msg'=>'密保问题回答错误，验证失败!'));
            exit;
        }
    }
    
    //重置密码
    public function resetpwd_ajax() {
        import('ORG.Util.Verify');
        if(Verify::isEmpty(I('newpwd'))==false
          || empty($this->uid)){
            ajaxf('数据出错');
        }
        $uid = $this->uid;
        $newpwd = md5(I('newpwd'));
        M('user')->where('id='.$uid)->setField('pwd', $newpwd);
        cookie('uid', NULL);
        ajaxf();
    }
    
    //邮箱重置密码
    public function mailpwd() {
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('email'))==false) {
            ajaxf('账号错误！');
        }
        $email = I('email');
        $resUser = M('user')->where("email='".$email."'")->find();
        if (!$resUser) {
            ajaxf('无此账号!');
        }
        $newcode = randCode(6);
        $ret = M('user')->where('id='.$resUser['id'])->setField('pwd', md5($newcode));
        if (!$ret) {
            ajaxf('重置失败!');
        }
        $resUserinfo = M('user_info')->where('uid='.$resUser['id'])->find();
        if (!$resUserinfo['protectemail']) {
            ajaxf('未设置密保邮箱!');
        }
        $host = "http://".$_SERVER['HTTP_HOST']."/Login";
        $body = "亲爱的".$resUserinfo['nickname'].",<br/>系统已为你重置了新密码，请不要再忘了哦~<br/>新密码:".$newcode."&nbsp;&nbsp;&nbsp;&nbsp;<a href='".$host."'>再次登陆</a>";
        $body = mailPostfix($body);
        $ret = think_send_mail($resUserinfo['protectemail'], $resUserinfo['nickname'], '密码重置', $body);
        if ($ret) {
            ajaxs(1, '系统已向你的密保邮箱发送邮件，快前去查收');
        }
        else {
            ajaxf('邮件发送失败，请尝试再次发送');
        }
    }
    
    //邮箱验证
    public function emailverify() {
        $code = I('code', 0);
        if ($code==1) {
            $token = I('token');
            $uid = $this->uid;
            if ($uid) {//已登陆
                $resEv = M('emailverify')->where("uid='".$uid."'")->find();
                $now = time();
                Log::write('resEv[token]:'.$resEv['token'].',token:'.$token.',now:'.$now.',resEv[ctime]:'.$resEv['ctime'].',elp:'.(time()-$resEv['ctime']));
                if ($resEv['token']==$token && ($now-$resEv['ctime'])<=86400) {
                    //设置标志
                    $resAc = M('account')->where('uid='.$uid)->find();
                    $ret = M('account')->where('uid='.$uid)->setField('emailverify', 1);
                    if ($resAc['emailverify']==1 || $ret) {
                        $this->assign('verify', 1);
                    }
                    else {
                        $this->assign('verify', 4);//验证失败
                    }
                }
                else {
                    $this->assign('verify', 2);//激活链接超时
                }
            }
            else {//未登陆
                $resEv = M('emailverify')->where("token='".$token."'")->find();
                if (!$resEv || (time()-$resEv['ctime'])>86400) {
                    $this->assign('verify', 2);
                    $this->display();
                    exit;
                }
                //是否已激活
                $account = M('account')->where('uid='.$resEv['uid'])->find();
                if ($account['emailverify']==1) {
                    $this->assign('verify', 1);
                    $this->display();
                    exit;
                }
                $resUser = M('user')->where("id=".$resEv['uid'])->find();
                if (!$resUser) {
                    $this->assign('verify', 2);
                    $this->display();
                    exit;
                }
                cookie('uid', $resUser['id'],'expire=0&domain='.getDomain());
                $resUif = M('user_info')->where("uid=".$resUser['id'])->find();
                if (!$resUif) {
                    $this->assign('verify', 2);
                    $this->display();
                    exit;
                }
                
                //设置标志
                $resAc = M('account')->where('uid='.$uid)->find();
                $ret = M('account')->where('uid='.$resUser['id'])->setField('emailverify', 1);
                if ($resAc['emailverify']==1 || $ret) {
                    $this->assign('verify', 1);
                }
                else {
                    $this->assign('verify', 4);//验证失败
                }
                
                //设置登陆状态
                $ld = array('identifer'=>'logined');
                M('user')->where('id='.$resEv['uid'])->save($ld);//设置已登陆状态
                $userinfoTab = M('user_info')->where('uid='.$resEv['uid'])->find();
                if($userinfoTab){
                    if($remember){
                        $identifier = md5(G_SALT . md5($email . G_SALT));
                        $token = md5(uniqid(rand(), TRUE));
                        $timeout = 60 * 60 * 24 * 7;
                        $dl = time() + $timeout;
                        //存储会话信息
                        $sd = array();
                        $sd['token'] = $token;
                        $sd['timeout'] = $dl;
                        M('user')->where('id='.$resEv['uid'])->save($sd);
                        cookie('auth', "$email:$identifier:$token", "expire=$timeout&domain=".getDomain());
                    }
                }
            }
        }
        else {
            $token = I('token');
            $uid = $this->uid;
            if ($uid) {//已登陆
                //是否已激活
                $account = M('account')->where('uid='.$uid)->find();
                if ($account['emailverify']==1) {
                    $this->assign('verify', 1);
                }
                else {
                    $this->assign('verify', 3);
                }
            }
            else {
                $resEv = M('emailverify')->where("token='".$token."'")->find();
                if (!$resEv || (time()-$resEv['ctime'])>86400) {
                    $this->assign('verify', 2);
                    $this->display();
                    exit;
                }
                //是否已激活
                $account = M('account')->where('uid='.$resEv['uid'])->find();
                if ($account['emailverify']==1) {
                    $this->assign('verify', 1);
                }
                else {
                    $this->assign('verify', 3);
                }
                
                //设置登陆状态
                cookie('uid', $resEv['uid'],'expire=0&domain='.getDomain());
                $ld = array('identifer'=>'logined');
                M('user')->where('id='.$resEv['uid'])->save($ld);//设置已登陆状态
                $userinfoTab = M('user_info')->where('uid='.$resEv['uid'])->find();
                if($userinfoTab){
                    if($remember){
                        $identifier = md5(G_SALT . md5($email . G_SALT));
                        $token = md5(uniqid(rand(), TRUE));
                        $timeout = 60 * 60 * 24 * 7;
                        $dl = time() + $timeout;
                        //存储会话信息
                        $sd = array();
                        $sd['token'] = $token;
                        $sd['timeout'] = $dl;
                        M('user')->where('id='.$resEv['uid'])->save($sd);
                        cookie('auth', "$email:$identifier:$token", "expire=$timeout&domain=".getDomain());
                    }
                }
            }
            
        }
        
        $this->display();
    }
}


?>